import { getRootWindow } from '@src/util/dom';
import { FORM_FIELD_CURRENCY_MAX, FORM_FIELD_CURRENCY_MIN } from '@src/model/const/Number.ts';
import MathUtil from '@src/util/math';
import { isEmpty } from '@src/util/type'

const rootWindow = getRootWindow(window);
const currencyList = rootWindow?.currencyList || []
import i18n from '@src/locales'
let currencyOption = (currencyList || []).map(item => {
    return {
        value: item.currency,
        label: `${item.currency} ${item.displayName}`
    }
})

function getCurrencyTypeName(currency = 'CNY') {
    let currencyObj = (currencyList || []).find(item => item.currency == currency)
    return `${currencyObj?.displayName}` 
}

function getCurrencyDisplayName(currency = 'CNY') {
    let currencyObj = (currencyList || []).find(item => item.currency == currency)
    return `${currencyObj?.currency || ''} ${currencyObj?.displayName || ''}` 
}

// 获取列表的国际货币字段展示
function getCurrencyDisplayView(currencyObj) {
    if(isEmpty(currencyObj)) return '';

    const { number = '', currency = '' } = currencyObj;

    if(!number && number !== 0) return '';

    return `${number} ${getCurrencyDisplayName(currency)}`
}

const exchangeMethodsOption = [
    {
        text: i18n.t('common.currency.bankExchangeRate'),
        value: 1
    },
    {
        text: i18n.t('common.currency.manulExchangeRate'),
        value: 2
    }
]

function validateCurrencyNumber(number, _this) {
    let count = MathUtil.decimalNumber(number);

    if(number > FORM_FIELD_CURRENCY_MAX || number < FORM_FIELD_CURRENCY_MIN) {
        _this.$platform.alert(_this.$t('common.form.tip.currency.overRange'));
        if(number > FORM_FIELD_CURRENCY_MAX) number = FORM_FIELD_CURRENCY_MAX;
        if(number < FORM_FIELD_CURRENCY_MIN) number = FORM_FIELD_CURRENCY_MIN;
    }
    if(count > 2) number = Number(number).toFixed(2);

    number = parseFloat(number + '');
    
    return number;
}

// 金额字段添加的货币参数后缀
const CURRENCY_SUFFIX = 'Currency';

// 合同相关金额字段
const contractAmountFieldNameList = ['otherAmount', 'discountAmount', 'contractAmount', 'quotationAmount', 'procureAmount'];
const productServiceAmount = ['serviceMoney'];
// 所有金额相关字段
const allAmountFieldNameList = [
    ...contractAmountFieldNameList, 
    ...productServiceAmount,
];

export {
    currencyOption,
    getCurrencyDisplayName,
    exchangeMethodsOption,
    validateCurrencyNumber,
    getCurrencyDisplayView,
    getCurrencyTypeName,
    CURRENCY_SUFFIX,
    contractAmountFieldNameList,
    allAmountFieldNameList,
}